package com.niit.mall.order.controller;


import com.niit.mall.api.domain.vo.ProductVO;
import com.niit.mall.common.api.CommonPage;
import com.niit.mall.common.api.CommonResult;
import com.niit.mall.common.domain.dto.PageDTO;
import com.niit.mall.common.utils.BeanUtils;
import com.niit.mall.common.utils.UserContext;
import com.niit.mall.order.domain.dto.*;
import com.niit.mall.order.domain.po.Order;
import com.niit.mall.order.domain.po.OrderReturnReason;
import com.niit.mall.order.domain.query.OrderQuery;
import com.niit.mall.order.domain.query.OrderReturnReasonQuery;
import com.niit.mall.order.domain.query.ReturnApplyQuery;
import com.niit.mall.order.domain.vo.ConfirmVO;
import com.niit.mall.order.domain.vo.OrderDetailVO;
import com.niit.mall.order.domain.vo.OrderVO;
import com.niit.mall.order.service.IOrderReturnApplyService;
import com.niit.mall.order.service.IOrderReturnReasonService;
import com.niit.mall.order.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单服务
 * @module pardo_mall
 * @BelongsProject: pardo_mall_backend
 * @BelongsPackage: com.niit.mall.order.controller
 * @Author: ChuXuan
 * @CreateTime: 2025-05-22  00:12
 * @Description: 订单请求控制器
 * @Version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/order")
@RequiredArgsConstructor
public class OrderController {

	private final IOrderService orderService;
	private final IOrderReturnApplyService orderReturnApplyService;
	private final IOrderReturnReasonService orderReturnReasonService;

	/**
	 * 创建订单的方法
	 *
	 * @param cartItemDTO 购物车项数据传输对象
	 * @return 订单创建结果的通用响应，成功时返回订单创建成功信息，失败时返回失败信息
	 */
	@PostMapping
	public CommonResult<ConfirmVO> createOrder( @RequestBody CartItemDTO cartItemDTO) {
		log.info("创建订单请求参数：{}", cartItemDTO);
		ConfirmVO confirmVO = orderService.createOrder(cartItemDTO);
		return CommonResult.success(confirmVO);
	}

	/**
	 * 根据订单ID查询我的订单信息。
	 * @param orderId 订单ID
	 * @return 返回包含订单视图对象的通用结果
	 */
	@GetMapping("{id}")
	public CommonResult<OrderVO> queryMyOrders(@PathVariable("id") Long orderId) {
		return CommonResult.success(BeanUtils.copyBean(orderService.getById(orderId), OrderVO.class));
	}

	/**
	 * 标记订单为支付成功状态。
	 * @param orderId 订单ID
	 * @return 支付成功的结果，包含成功标志
	 */
	@PutMapping("/pay/{id}")
	public CommonResult payOrder(@PathVariable("id") Long orderId) {
		orderService.markOrderPaySuccess(orderId);
		return CommonResult.success(true);
	}

	/**
	 * 查询我的订单列表
	 * @return 分页订单视图对象
	 */
	@GetMapping
	public CommonResult<List<OrderDTO>> queryMyOrders() {
		Long id = UserContext.getUser();
		List<Order> list = orderService.lambdaQuery().eq(Order::getUserId, id).list();
		return CommonResult.success(BeanUtils.copyList(list, OrderDTO.class));
	}

	/**
	 * 分页查询所有订单
	 * @param query 查询参数
	 * @return 分页订单视图对象
	 */
	@GetMapping("/page")
	public CommonResult<PageDTO<OrderDTO>> queryAllOrders(OrderQuery query) {
		log.info("请求的参数：{}", query);
		PageDTO<OrderDTO> page = orderService.queryAllOrders(query);
		return CommonResult.success(page);
	}

	/**
	 * 根据订单id获取订单详情
	 */
	@GetMapping("/detail/{id}")
	public CommonResult<OrderDetailDTO> queryOrderInfo(@PathVariable("id") Long id) {
		OrderDetailDTO orderDetailDTO = orderService.getDetailById(id);
		return CommonResult.success(orderDetailDTO);
	}

	/**
	 * 分页查询所有退单
	 * @param query 查询参数
	 * @return 分页退单视图对象
	 */
	@GetMapping("/refund/page")
	public CommonResult<PageDTO<OrderReturnApplyDTO>> queryAllRefund(ReturnApplyQuery query) {
		log.info("请求的参数：{}", query);
		PageDTO<OrderReturnApplyDTO> page = orderReturnApplyService.queryAllRefund(query);
		return CommonResult.success(page);
	}

	/**
	 * 根据退单id获取退单详情
	 * @param id 退单id
	 * @return 退单详情
	 */
	@GetMapping("/refund/detail/{id}")
	public CommonResult<OrderReturnApplyDetailDTO> queryRefundInfo(@PathVariable("id") Long id) {
		OrderReturnApplyDetailDTO orderReturnApplyDetailDTO = orderReturnApplyService.getDetailById(id);
		return CommonResult.success(orderReturnApplyDetailDTO);
	}

	/**
	 * 根据原因id获取退单原因
	 * @param id 原因id
	 * @return 退单原因
	 */
	@GetMapping("/reason/{id}")
	public CommonResult<OrderReturnReasonDTO> queryReasonById(@PathVariable("id") Long id) {
		return CommonResult.success(BeanUtils.copyBean(orderReturnReasonService.getById(id), OrderReturnReasonDTO.class));
	}

	/**
	 * 获取所有退单原因分页列表
	 * @return 退货原因视图对象
	 */
	@GetMapping("/reason/page")
	public CommonResult<PageDTO<OrderReturnReasonDTO>> queryAllReason(OrderReturnReasonQuery query) {
		return CommonResult.success(orderReturnReasonService.queryAllReason(query));
	}

	/**
	 * 修改退单原因
	 * @param orderReturnReasonDTO 退货原因数据传输对象
	 */
	@PutMapping("/reason")
	public CommonResult updateReason(@RequestBody OrderReturnReasonDTO orderReturnReasonDTO) {
		orderReturnReasonDTO.setUpdateTime(LocalDateTime.now());
		return orderReturnReasonService.updateById(BeanUtils.copyBean(orderReturnReasonDTO, OrderReturnReason.class)) ?
				CommonResult.success(true) : CommonResult.failed();
	}

	/**
	 * 添加退货原因
	 * @param orderReturnReasonDTO 退货原因数据传输对象
	 */
	@PostMapping("/reason")
	public CommonResult addReason(@RequestBody OrderReturnReasonDTO orderReturnReasonDTO) {
		return orderReturnReasonService.save(BeanUtils.copyBean(orderReturnReasonDTO, OrderReturnReason.class)) ?
				CommonResult.success(true) : CommonResult.failed();
	}

	/**
	 * 逻辑删除退货原因
	 * @param id 退货原因id
	 */
	@PutMapping("/reason/delete/{id}")
	public CommonResult deleteReason(@PathVariable Long id) {
		return orderReturnReasonService.removeById(id) ?
				CommonResult.success(true) : CommonResult.failed();
	}

	/**
	 * 根据类型查询订单列表
	 *
	 * @param type 订单类型
	 * @return 返回包含订单数据的结果对象，类型为{@link CommonResult}
	 */
	@GetMapping("/type/{type}")
	public CommonResult<Map<Long, List<OrderDetailVO>>> queryOrdersByType(@PathVariable("type") Integer type) {
		return CommonResult.success(orderService.queryOrdersByType(type));
	}

	/**
	 * 查询最近完成的订单列表
	 *
	 * @return 返回包含最近完成订单的列表的通用结果对象
	 */
	@GetMapping("/recently")
	public CommonResult<Map<Long, List<OrderDetailVO>>> queryRecentlyOrder() {
		Long userId = UserContext.getUser();
		// 1. 查询最近完成的3个订单
		List<Order> orderList = orderService.lambdaQuery()
				.eq(Order::getUserId, userId)
				.eq(Order::getStatus, 4)
				.orderByDesc(Order::getPayTime)
				.last("limit 3")
				.list();

		// 2. 组装结果
		Map<Long, List<OrderDetailVO>> map = new HashMap<>();
		for (Order order : orderList) {
			List<OrderDetailVO> detailList = orderService.getAllProductByOrderId(order.getId()).get(order.getId());
			map.put(Long.valueOf(order.getOrderNumber()), detailList);
		}
		return CommonResult.success(map);
	}

	/**
	 * 查询今日订单数量
	 * @return 订单数量
	 */
	@GetMapping("/count/today")
	public CommonResult<Long> queryToDayOrderCount() {
		return CommonResult.success(orderService.queryTodayOrderCount());
	}

	/**
	 * 查询本月订单数量
	 * @return 订单数量
	 */
	@GetMapping("/count/tomonth")
	public CommonResult<Long> queryToMonthOrderCount() {
		return CommonResult.success(orderService.queryTomonthOrderCount());
	}

	/**
	 * 查询上月订单数量
	 * @return 订单数量
	 */
	@GetMapping("/count/last_month")
	public CommonResult<Long> queryLastMonthOrderCount() {
		return CommonResult.success(orderService.queryLastMonthOrderCount());
	}

	// 常购清单 TODO: 待实现
	// 基于购物车生成的订单 TODO: 待实现
//	@PutMapping("/cart")

	// 订单评论 TODO: 待实现
	// 订单退款 TODO: 待实现
	// 订单发货 TODO: 待实现
	// 订单收货 TODO: 待实现
}
